var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
var moment = require('moment');
const rp = require('request-promise-native');
let { GetopenID_Url, appId, AppSecret } = require('../config');
let { getBase64, setBase64, isgender, FormatData } = require('../util.js');
let { isUser, addUser, updataUser, GetUsersById, getRegionAll, getRegionInfo, addOrder, setRegionState, getOrderssById, setOrderState,
  getbeginMoneyUser, userRecharge, getOrderList, addWash, updateWash
} = require('../mysql/users')
/**
 * 所有关于用户的请求接口
 */
const methodsToken = [
  '/addOrder',
  '/getbeginMoneyUser',
  '/userRecharge',
  '/getOrderList',
  '/addWash',
  '/updateWash',
  '/payment'
];
router.post("*", (req, res, next) => {
  // 判断token是否存在
  if (methodsToken.indexOf(req.url) >= 0) {
    // 获取用户token
    let userToken = req.body.token;
    if (!userToken) {
      return res.json({
        code: 0,
        data: "请先登录"
      });
    } else {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  } else {
    let userToken = req.body.token;
    if (userToken) {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  }
  next();
})
/**
 *  获取openid
 */
router.post('/login', async (req, res, next) => {
  let { nickName, gender, avatarUrl, userId, Token } = req.body;
  let url = `${GetopenID_Url}appid=${appId}&secret=${AppSecret}&js_code=${req.body.code}&grant_type=authorization_code`;
  let userCode = await rp({
    method: 'GET', url, json: true
  })
  let isUserInfo = await isUser({
    openid: userCode.openid
  })
  if (isUserInfo.length) {
    await updataUser(isUserInfo[0].userId, {
      userName: nickName,
      userSex: isgender(gender),
      userUrl: avatarUrl
    })
    res.json({
      code: 1,
      data: {
        Token: getBase64(isUserInfo[0].userId),
        userInfo: isUserInfo[0]
      }
    })
  } else {
    let data = await addUser({
      openid: userCode.openid,
      userName: nickName,
      userSex: isgender(gender),
      userUrl: avatarUrl
    })
    res.json({
      code: 1,
      data: {
        Token: getBase64(data.insertId),
        userInfo: await GetUsersById(data.insertId)
      }
    })
  }
});
/**
 * 返回用户信息
 */
router.post('/userInfoById', async (req, res, next) => {
  let { userId } = req.body;
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回所有澡堂信息
 */
router.get('/getRegionAll', async (req, res, next) => {
  let data = await getRegionAll();
  res.json({
    code: 1,
    data: FormatData(data, {
      'regionImgs': 'json',
      'regionDate': 'date'
    })
  })
})
/**
 * 获取澡堂详情
 */
router.post('/getRegionInfo', async (req, res, next) => {
  let { regionId } = req.body;
  let data = await getRegionInfo(regionId);
  res.json({
    code: 1,
    data: FormatData(data, {
      'regionImgs': 'json',
      'regionDate': 'time'
    })
  })
})
/**
 * 添加预约
 */
router.post('/addOrder', async (req, res, next) => {
  let { orderName, orderPhone, orderIntroduce, userId, regionId } = req.body;
  let info = await addOrder({
    orderName, orderPhone, orderIntroduce, userId, regionId
  });
  await setRegionState(regionId, {
    regionState: '已预约'
  })
  let [data] = await getOrderssById(info.insertId)
  setTimeout(async () => {
    let [orderItem] = await getOrderssById(info.insertId)
    if (orderItem.orderState == 1) {
      await setOrderState(info.insertId, {
        orderState: '0'
      })
      await setRegionState(regionId, {
        regionState: '空闲'
      })
    }
  }, 60 * 10 * 1000)
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "错误"
    })
  } else {
    res.json({
      code: 1,
      data: data
    })
  }
})
/**
 * 获取用户余额
 */
router.post('/getbeginMoneyUser', async (req, res, next) => {
  let { userId } = req.body;
  let data = await getbeginMoneyUser(userId)
  res.json({
    code: 1,
    data: data[0]
  })
})
/**
 * 充值
 */
router.post('/userRecharge', async (req, res, next) => {
  let { userId, Money } = req.body;
  let data = await userRecharge(userId, {
    Money
  })
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取个人预约信息
 */
router.post('/getOrderList', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let { data, count } = await getOrderList(num, limit, { userId });
  if (data.length) {
    if (data.length) {
      res.json({
        code: 1,
        data: FormatData(data, {
          'orderDate': 'date',
          'regionImgs': 'json',
          'regionDate': 'time'
        }),
        count: count
      })
    } else {
      res.json({
        code: 1,
        data: [],
        count: count
      })
    }
  } else {
    res.json({
      code: 0,
      data: [],
      count: count
    })
  }
})
/**
 * 添加洗澡记录
 */
router.post('/addWash', async (req, res, next) => {
  let { regionId, userId, type, orderId } = req.body;
  let info = await addWash({
    regionId, userId
  });
  if (type == 2) {
    await setOrderState(orderId, {
      orderState: '2'
    })
  }
  await setRegionState(regionId, {
    regionState: '使用中'
  })
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "错误"
    })
  } else {
    res.json({
      code: 1,
      data: info
    })
  }
})
/**
 * 完成洗澡
 */
router.post('/updateWash', async (req, res, next) => {
  let { regionId, userId, type, orderId, washTime, washId } = req.body;
  let data = await getRegionInfo(regionId);
  let hour = (washTime / 3600)
  let washMon = (data.regionPrice * hour).toFixed(2)
  let info = await updateWash(washId, {
    regionId, userId, washMon, washTime
  });
  if (type == 2) {
    await setOrderState(orderId, {
      orderState: '3'
    })
  }
  await setRegionState(regionId, {
    regionState: '空闲'
  })
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "错误"
    })
  } else {
    res.json({
      code: 1,
      data: {
        ...info,
        washMon
      }
    })
  }
})
/**
 * 支付扣钱
 */
router.post('/payment', async (req, res, next) => {
  let { userId, Money } = req.body;
  let data = await userRecharge(userId, {
    Money: - Money
  })
  res.json({
    code: 1,
    data
  })
})

module.exports = router;
